from datetime import datetime
import random
import re

from flask import current_app, jsonify
from flask import make_response
from flask import request
from flask import session

from info import redis_store, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blu
from info import constants

@passport_blu.route('/logout',methods=['POST'])
def logout():
    # 登出
# 1.清除session
    session.pop('nick_name',None)
    session.pop('mobile',None)
    session.pop('user_id',None)
    return jsonify(errno=RET.OK, errmsg="OK")


@passport_blu.route('/login',methods=['POST'])
def login():
# 登录功能
# 1.接受参数
    mobile = request.json.get('mobile')
    password = request.json.get('password')
# 2.判断参数
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
# 3.从数据库查询出指定用户
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")
# 4.判断用户是否存在并判断密码
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在")
    if not user.check_password(password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")
# 5.状态保持
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    # 记录用户最后一次登录时间
    user.last_login = datetime.now()


    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        # 5. 登录成功
    return jsonify(errno=RET.OK, errmsg="OK")


@passport_blu.route('/register',methods=['GET','POST'])
def register():
# 注册功能
# 1.接受参数
    mobile = request.json.get('mobile')
    smscode = request.json.get('smscode')
    password = request.json.get('password')
# 2.校验参数
    if not all([mobile,smscode,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺少')
# 3.判断验证码是否输入正确
    try:
        real_smscode = redis_store.get('SMS_'+mobile).decode()
    except Exception as e:
        return jsonify(errno = RET.DATAERR,errmsg= '读取失败')
    if not smscode:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码过期")
    if not real_smscode == smscode:
        return jsonify(errno = RET.PARAMERR,errmsg='手机验证码错误')
        # 删除短信验证码
    try:
        redis_store.delete("SMS_" + mobile)
    except Exception as e:
        current_app.logger.error(e)
# 4初始化模型
    user = User()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = password
# 5.保存到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        # 数据保存错误
        return jsonify(errno=RET.DATAERR, errmsg="数据保存错误")


    return jsonify(errno=RET.OK, errmsg="OK")


@passport_blu.route('/smscode',methods=['GET','POST'])
def send_sms():
# 1.接受参数
    mobile = request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')
# 2.校验参数
    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
# 3.检验手机号
    if not re.match('1[3578][0-9]{9}$',mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
# 4.通过传入的图片验证码区验证内容
    try:
        real_image_code = redis_store.get("ImageCode_" + image_code_id)
        if real_image_code:
            real_image_code = real_image_code.decode()
            redis_store.delete("ImageCode_" + image_code_id)
    except Exception as e:
            current_app.logger.error(e)
            # 获取图片验证码失败
            return jsonify(errno=RET.DBERR, errmsg="获取图片验证码失败")

    if not real_image_code:
        # 验证码已过期
        return jsonify(errno=RET.NODATA, errmsg="验证码已过期")

    if image_code.lower() != real_image_code.lower():
        # 验证码输入错误
        return jsonify(errno=RET.DATAERR, errmsg="验证码输入错误")
# 5.检验手机是否已经注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg="该手机已被注册")
# 6.生成短信验证码
    result = random.randint(0,999999)
    sms_code = '%06d' %result
    current_app.logger.debug("短信验证码的内容：%s" % sms_code)
    # result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], "1")
    # if result != 0:
    #         # 发送短信失败
    #         return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")
# 7.保存在redis中
    try:
        redis_store.set('SMS_'+mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
            current_app.logger.error(e)
            # 保存短信验证码失败
            return jsonify(errno=RET.DBERR, errmsg="保存短信验证码失败")
# 8. 返回发送成功的响应
    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blu.route('/image_code')
def get_image_code():

    # 1.获取图片编号
    code_id = request.args.get('code_id')
    # 2.生成图片验证码
    name, text, image = captcha.generate_captcha()
    # 3.保存图片验证码内容
    try:
        redis_store.setex('ImageCode_'+code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
    except Exception as e:
        current_app.logger.error(e)
        return make_response(jsonify(errno=RET.DATAERR, errmsg='保存图片验证码失败'))
    # 4.返回响应内容
    resp = make_response(image)
    resp.headers['Content-Type'] = 'image/jpg'
    return resp